<template>
	<view class="u-skeleton">
		<view class="bodystyle" :key="timerform">
			<u-form labelPosition="left" :model="defaultForm" :rules="rules" ref="uForm">
				<view v-for="(item,index) in fields" :key="index">
					<u-form-item :labelWidth="170" :label="item.label" :prop="item.vModel"
						:rules="[{ required: (formAuth[item.vModel]==2&&item.required)?true:false, message: item.placeholder, trigger: item.tag==='el-select'?'change':'blur' }]">
						{{item.tag}}
						<view v-if="item.tag==='el-input'&&item.type!=='textarea'">
							<u-input border="surround" :style="item.style.width?item.style:defaultStyle"
								:disabled="item.disabled" :maxlength="item.maxlength?item.maxlength:256"
								:placeholder="item.placeholder" v-model="defaultForm[item.vModel]">
							</u-input>
						</view>
						<view v-if="item.tag=='el-select'">
							<view @click="openSelect(item.tag)">点击选择</view>
							<view v-if="showSelect">
								<u-picker @cancel="showSelect=false" @confirm="comfirnSelect" :show="showSelect"
									:columns="[item.options]" keyName="label"></u-picker>
							</view>
						</view>
						<view v-if="item.tag=='el-switch'">
							<u-switch :placeholder="item.placeholder" v-model="defaultForm[item.vModel]"
								:disabled="item.disabled">
							</u-switch>
						</view>
						<view v-if="item.tag=='fc-date-duration'">
							<view @click="openRangeDate(item.tag)">点击选择日期</view>
							<view v-if="showRange">
								<u-calendar :show="showRange" :mode="mode" @confirm="confirmRangeDate"
									@close="showRange=false"></u-calendar>
							</view>
						</view>
						<view v-if="item.tag=='el-date-picker'">
							<view @click="openSingleDate(item.tag)">点击选择日期</view>
							<view v-if="showSingle">
								<u-calendar :show="showSingle" :mode="mode" @confirm="confirmSingleDate"
									@close="showSingle=false"></u-calendar>
							</view>
						</view>
						<view v-if="item.tag=='fc-time-duration'">

						</view>
						<view v-if="item.tag=='el-slider'">
							<u-slider :disabled="item.disabled" :style="item.style?item.style:defaultStyle"
								:min="item.min" :max="item.max" :step="item.step"
								:value="defaultForm[item.vModel]"></u-slider>
							<!-- <slider :disabled="item.disabled" :style="item.style?item.style:defaultStyle"
								:min="item.min" :max="item.max" :step="item.step" :value="defaultForm[item.vModel]" /> -->
						</view>
						<view v-if="item.tag=='el-radio-group'">
							<u-radio-group @change="$forceUpdate()" v-model="defaultForm[item.vModel]"
								:disabled="item.disabled">
								<u-radio v-for="i in item.options" :key="i.value" :label="i.value" size="30">
								</u-radio>
							</u-radio-group>
						</view>
						<view v-if="item.tag=='el-cascader'">

						</view>
						<view v-if="item.tag=='el-input-number'">
							<u-input border="surround" :style="item.style.width?item.style:defaultStyle"
								:disabled="item.disabled" type="number" :placeholder="item.placeholder"
								v-model="defaultForm[item.vModel]">
							</u-input>
						</view>
						<view v-if="item.tag=='el-rate'">
							<u-rate size="30" :style="item.style.width ? item.style : defaultStyle"
								v-model="defaultForm[item.vModel]" :disabled="item.disabled"></u-rate>
						</view>
						<view v-if="item.tag==='el-input'&&item.type==='textarea'">
							<u-input :style="item.style.width?item.style:defaultStyle" :disabled="item.disabled"
								:rows="2" :maxlength="item.maxlength?item.maxlength:256" :placeholder="item.placeholder"
								:autosize="item.autosize" :show-word-limit="item['show-word-limit']"
								v-model="defaultForm[item.vModel]" border="none"></u-input>
						</view>
						<view v-if="item.tag=='fc-amount'">
							<u-input border="surround" :style="item.style.width?item.style:defaultStyle"
								:disabled="item.disabled" type="number" :placeholder="item.placeholder"
								v-model="defaultForm[item.vModel]">
							</u-input>
						</view>
						<view v-if="item.tag=='el-checkbox-group'">
							<u-checkbox-group size="30" :disabled="item.disabled" v-model="defaultForm[item.vModel]">
								<u-checkbox v-for="(check, ind) in item.options" :key="ind + 'check'"
									:label="check.label" :value="check.value">
								</u-checkbox>
							</u-checkbox-group>
						</view>
						<view v-if="item.tag=='el-time-picker'">
							<view @click="openSingleTime(item.tag)">点击选择时间</view>
							<view v-if="showSingletime">
								<!-- <u-datetime-picker @cancel="showSingletime=false" @confirm="comfirnSingletime"
									mode="time" :show="showSingletime"
									v-model="defaultForm[item.vModel]"></u-datetime-picker> -->
							</view>
						</view>
						<view v-if="item.tag=='el-upload'">
							<u-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="1" multiple
								:maxCount="10"></u-upload>
						</view>
					</u-form-item>
				</view>
			</u-form>
		</view>
	</view>
</template>

<script>
	import PROVINCE from './province';
	export default {
		name: 'formdetail',
		props: {
			formData: {
				type: Object,
				default () {
					return {};
				}
			},
			formAuth: {
				type: Object,
				default () {
					return {};
				}
			},
			applierChooseList: {
				type: Array,
				default () {
					return [];
				}
			},
			processKey: {
				type: String,
				default () {
					return '';
				}
			}
		},
		data() {
			return {
				fileList: [],
				show: true,
				value1: null,
				mode: 'range',
				timerform: null,
				showRange: false,
				myHeaders: {
					Authorization: '',
					TenantId: 0
				},
				checkModel: {},
				isCheck: false,
				userTimer: '',
				PROVINCE: PROVINCE,
				loading: false,
				defaultStyle: {
					width: '100%'
				},
				defaultForm: {},
				tableForm: {},
				fileList: [],
				rules: {},
				fields: [],
				approveData: {},
				selectUserData: {},
				selectedProcessKey: '',
				isEmpty: false,
				mark: '',
				tableMark: null,
				tableIndex: null,
				formTag: '',
				showSingle: false,
				showSingletime: false,
				showSelect: false
			}
		},
		created() {
			console.log('Kdpajkpdjpajdpajdp');
			this.actionData()
		},
		methods: {
			actionData() {
				this.defaultForm = {};
				this.tableForm = {};
				this.rules = {};
				this.fields = [];
				this.formData.fields.forEach(field => {
					if (field.dataSources === "dict") {
						this.$request(this.$api['workbench/getParam'], {
							id: field.api
						}, res => {
							field.options = [];
							data.forEach(e => {
								field.options.push({
									label: e.dictName,
									value: e.dictCode,
								});
							});
						})
					} else if (field.dataSources === "api") {
						field.options;
						uni.$u.http.request({
						    url: field.api, 
							methods:'post',
						    data: {},
						    header: {
						        Authorization: field.token
						    },
						    success: (res) => {
						        field.options = res.data;
						    }
						});
						// axios({
						// 	method: 'post',
						// 	url: field.api,
						// 	data: {},
						// 	headers: {
						// 		Authorization: field.token
						// 	},
						// }).then(function(res) {
						// 	field.options = res.data;
						// });
					}
					if (field.tag !== 'grid') {
						if (this.formAuth[field.vModel] == 1) {
							field.disabled = true;
							this.fields.push(field);
						} else if (this.formAuth[field.vModel] == 2) {
							field.disabled = false;
							this.fields.push(field);
						} else if (this.formAuth[field.vModel] == undefined) {
							field.disabled = true;
							this.fields.push(field);
						} else {
							field.hide = true;
						}
						// this.fields.push(field);
						this.$set(this.defaultForm, field.vModel, field.defaultValue == undefined ? null : field
							.defaultValue);
					} else {
						field.children.forEach(e => {
							if (this.formAuth[e.vModel] == 1) {
								e.disabled = true;
								this.fields.push(e);
							} else if (this.formAuth[e.vModel] == 2) {
								e.disabled = false;
								this.fields.push(e);
							} else if (this.formAuth[e.vModel] == undefined) {
								e.disabled = true;
								this.fields.push(e);
							} else {
								e.hide = true;
							}
							// this.fields.push(e);
							this.$set(this.defaultForm, e.vModel, e.defaultValue == undefined ? null : e
								.defaultValue);
						});
					}
					if (field.tag == "fc-input-table") {
						let obj = {};
						field.children.forEach(e => {
							this.$set(obj, e.vModel, !e.defaultValue ? null : e.defaultValue);
							this.$set(this.tableForm, e.vModel, e.defaultValue == undefined ? null : e
								.defaultValue);
						});
						this.defaultForm[field.vModel] = [obj];
					}
				});
				console.log(this.defaultForm, 'dmoajdajhdoajdo');
				console.log('djoaoooooooo--------');
				setTimeout(() => {
					this.applierChooseList.forEach(e => {
						this.approveData[e.paramKey] = [];
						this.selectUserData[e.paramKey] = '';
					});
				console.log(this.fields,'fieldss')
				}, 100);
			},
			comfirnSelect(e) {
				this.showSelect = false;
			},
			openSelect(e) {
				this.formTag = e;
				this.showSelect = true;
			},
			getData(e) {
				console.log(e);
			},
			comfirnSingletime(e) {
				console.log(e, '====');
				this.showSingletime = false;

			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			openSingleTime(e) {
				this.formTag = e;
				this.showSingletime = true;
			},
			openRangeDate(e) {
				this.mode = 'range';
				this.formTag = e;
				this.showRange = true;
			},
			openSingleDate(e) {
				this.mode = 'single';
				this.formTag = e;
				this.showSingle = true;
			},
			confirmSingleDate(e) {
				console.log(e, '这是啥');
			},
			confirmRangeDate(e) {
				console.log(e, '这是啥');
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'http://192.168.2.21:7001/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			getSelectData(e, istable, index, tableKey = null) {
				console.log(e, istable, index, tableKey, this.defaultForm, '--------');
				let param = {};
				if (e.param) {
					let that = this;
					e.param.forEach(p => {
						if (that.defaultForm[p.field]) {
							param[p.field] = that.defaultForm[p.field];
						}
						if (istable && !that.defaultForm[p.field]) {
							param[p.field] = that.defaultForm[tableKey][index][p.field];
						}
					});
				}
				console.log(param, '这是获取到得参数');
				if (e.dataSources === "dict") {
					this.$request(this.$api['workbench/getParam'], {
						id: e.api
					}, res => {
						data => {
							let arr = [];
							data.forEach(e => {
								arr.push({
									label: e.dictName,
									value: e.dictCode,
								});
							});
							e.options = arr;
						}
					})
				} else if (e.dataSources === "api") {
					uni.$u.http.request({
						url: e.api,
						data: param,
						methods: 'post',
						header: {
							Authorization: e.token
						},
						success: (res) => {
							e.options = res.data;
						}
					});
				}
			},
			checkData(required, val, p, vmodel) {
				if (this.isCheck && required && !val) {
					this.checkModel[vmodel] = true;
					return p;
				}
				this.checkModel[vmodel] = false;
				return "";
			},
			add(item) {
				let obj = {};
				item.children.forEach(e => {
					this.$set(obj, e.vModel, !e.defaultValue ? null : e.defaultValue);
				});
				this.defaultForm[item.vModel].push(obj);
			},
			del(item, index, row) {
				if (this.defaultForm[item.vModel].length < 2) {
					this.$message.info("当前表格只有一行，无法删除");
					return;
				}
				this.defaultForm[item.vModel].splice(index, 1);
			},
			showFiles(e) {
				window.open(e);
			},
			markfile(e, type = null, index = null) {
				if (type && index !== null) {
					this.mark = type;
					this.tableMark = e;
					this.tableIndex = index;
				} else {
					this.mark = e;
				}
			},
			onProgress(e) {},
			beforeUpload(e) {
				const isOver = e.size / 1024 / 1024 < this.mark.fileSize;
				// 限制文件上传大小
				if (!isOver) {
					this.$message.error('上传图片大小不能超过 ' + this.mark.fileSize + 'MB!');
					return false;
				}
			},
			beforeUploadTable(e) {
				const isOver = e.size / 1024 / 1024 < this.tableMark.fileSize;
				// 限制文件上传大小
				if (!isOver) {
					this.$message.error('上传图片大小不能超过 ' + this.tableMark.fileSize + 'MB!');
					return false;
				}
			},
			openChoose(e) {
				this.$refs.userchoose.dialogVisible = true;
				this.selectedProcessKey = e;
				this.$refs.userchoose.timer = new Date().getTime();
				this.approveData[this.selectedProcessKey].length && this.$refs.userchoose.setCheckedKeys(this.approveData[
					this.selectedProcessKey]);
			},
			// 条件回调
			getConditionData(e) {
				if (!e) {
					return false;
				}
				let arr = [];
				let users = [];
				e.forEach(r => {
					if (r.primaryCode.indexOf('org') === -1) {
						arr.push(r.primaryId);
						users.push(r.label);
					}
				});
				this.approveData[this.selectedProcessKey] = arr;
				this.selectUserData[this.selectedProcessKey] = users.join(' / ');
				this.userTimer = new Date().getTime();
				console.log(e, 'www', this.approveData, this.selectUserData);
			},
			submitForm(formName) {
				this.isCheck = true;
				setTimeout(() => {
					let checks = false;
					Object.keys(this.checkModel).forEach(e => {
						if (this.checkModel[e]) {
							checks = true;
							// console.log(this.checkModel, checks, this.checkModel[e], '检测');
						}
					});
					if (checks) {
						this.$message.error('您有必填项未填');
						return;
					}
					this.$refs[formName].validate(valid => {
						if (valid) {
							this.isEmpty = false;
							this.applierChooseList.forEach(e => {
								if (!this.approveData[e.paramKey].length) {
									this.isEmpty = true;
								}
							});
							if (this.isEmpty) {
								this.$message.error('请配置所有节点用户');
								return false;
							}
							this.loading = true;
							this.$api['workflow/startProcess']({
								formData: this.defaultForm,
								processKey: this.processKey,
								approveData: this.approveData
							}).then(data => {
								this.$emit('startProcess', true);
								this.$message.success('发起审批成功');
								this.loading = false;
							}).catch(e => {
								this.loading = false;
							});
						}
					});
				}, 100);
			},
			resetForm(formName) {
				this.$refs[formName].resetFields();
			},
			handleRemoveFile(file) {
				let index = this.defaultForm[this.mark.vModel].findIndex(e => {
					return e.fileUrl == file.fileUrl;
				});
				this.defaultForm[this.mark.vModel].splice(index, 1);
			},
			getImgList(imgs) {
				let imgarr = [];
				imgs.forEach(e => {
					imgarr.push(e.fileUrl);
				});
				return imgarr;
			},
			handleRemoveTable(file) {
				console.log(file);
				let index = this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].findIndex(e => {
					return e.fileUrl == file.response.data[0].fileUrl;
				});
				this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].splice(index, 1);
				console.log(index, this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel]);
			},
			handleSuccessTable(e) {
				if (!this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel]) {
					this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel] = [];
				}
				this.defaultForm[this.mark.vModel][this.tableIndex][this.tableMark.vModel].push({
					fileUrl: e.data[0].fileUrl,
					fileName: e.data[0].fileName
				});
			},
			handlePreviewTable(file) {
				console.log(file);
			},
			handleRemove(file) {
				console.log(file);
				let index = this.defaultForm[this.mark.vModel].findIndex(e => {
					return e.fileUrl == file.response.data[0].fileUrl;
				});
				this.defaultForm[this.mark.vModel].splice(index, 1);
				console.log(index, this.defaultForm[this.mark.vModel]);
			},
			handleSuccess(e) {
				if (!this.defaultForm[this.mark.vModel]) {
					this.defaultForm[this.mark.vModel] = [];
				}
				this.defaultForm[this.mark.vModel].push({
					fileUrl: e.data[0].fileUrl,
					fileName: e.data[0].fileName
				});
			},
			handlePreview(file) {
				console.log(file);
			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
			},
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			}
		},
	}
</script>

<style lang="scss" scoped>

</style>